package com.leyou.auth.service.impl;

import com.leyou.auth.dto.UserDetail;
import com.leyou.auth.service.UserAuthService;
import com.leyou.auth.utils.JwtUtils;
import com.leyou.common.exception.MyException;
import com.leyou.user.client.UserClient;
import com.leyou.user.dto.UserDTO;
import feign.FeignException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
@Service
public class UserAuthServiceImpl implements UserAuthService {
    @Autowired
    private UserClient userClient;
    @Autowired
    private JwtUtils jwtUtils;
    @Override
    public void login(String username, String password, HttpServletResponse response) {
        UserDTO userDTO=null;
        try {
            userDTO= userClient.queryUserByPhoneAndPassword(username, password);
            System.out.println(userDTO);
        } catch (FeignException e) {
            new MyException(e.status(), e.getMessage());
        }
        UserDetail userDetail = UserDetail.of(userDTO.getId(), userDTO.getUsername());
        //生成token
        String token = jwtUtils.createJwt(userDetail);
        //创建cookie
        Cookie cookie = new Cookie("LY_TOKEN",token);
        //绑定的域名
        cookie.setDomain("leyou.com");
        //当前域下的适配路径
        cookie.setPath("/");
        //对前端的script技术隐藏，提升安全性
        cookie.setHttpOnly(true);
        response.addCookie(cookie);


    }
}
